//
//  AppDelegate.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/1.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "AppDelegate.h"
#import "MenuViewController.h"
#import "LoginViewController.h"
#import "Utils.h"
//#import "MobClick.h"
#import "UMSocial.h"
#import "ShareKEY.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "WeiboSDK.h"
#import "MobClick.h"
#import "BuaatVolunteerServerSDK.h"
#import "CityFileManager.h"
@interface AppDelegate ()<UIAlertViewDelegate>
@property(strong,nonatomic)NSDictionary *versionInfo;
@end

@implementation AppDelegate
+(AppDelegate *)getInstance {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //mob
    [[BuaatVolunteerServerSDK sharedInstance]setClientId:BuaatVolunteerSDKClientId appKey:BuaatVolunteerSDKPublicKey];
//    [self setupMob];
    // Override point for customization after application launch.
    [[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18*SCREEN_WIDTH/320]}];
    
    //检查版本更新
    [self checkVersion];
    //友盟
    [self setupUMeng];
    
    
    
    //百度地图
    [self setupBaiduMap];
    
    

    
    self.window=[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    self.window.backgroundColor=[UIColor whiteColor];
    [self.window makeKeyAndVisible];
    MenuViewController *menuVC = [[MenuViewController alloc]init];
    [AppDelegate getInstance].menuVC= menuVC;
    self.window.rootViewController = menuVC;
    
    return YES;
}


-(void)setupMob{
    /*
    [Analysis setRequestURLWithSendClientDataURL:@"http://123.59.61.11:38081/api"
                              getReportPolicyURL:@"http://123.59.61.11:38081/policy"
                             getFeedbackReplyURL:@"http://123.59.61.11:38081/reply"
                                getUpdateInfoURL:@"http://123.59.61.11:38081/check"];
    [Analysis startWithAppkey:AnalyAppKey reportPolicy:REALTIME channelId:@"App Store"];
    */
//    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    // app版本
//    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
//    NSString *appInfo=[NSString stringWithFormat:@"%@.%@",app_Version,app_build];
//    [Analysis setAppVersion:appInfo];
//    
//    //设置崩溃报告和日志打印（可选）
//    [Analysis setCrashReportEnabled:YES];  //默认是开启状态
//    [Analysis setLogEnabled:YES];          //默认不开启
}


-(void)setupUMeng{
//    [MobClick startWithAppkey:UMengAppKey reportPolicy:REALTIME   channelId:@""];
//     [MobClick startWithAppkey:@"555308b3e0f55aef9e0050b4" reportPolicy:(ReportPolicy) REALTIME channelId:nil];
    
//    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
//    [MobClick setAppVersion:version];
     [MobClick startWithAppkey:UMengAppKey reportPolicy:BATCH channelId:@"Web"];
    
    
    [UMSocialData setAppKey:UMengAppKey];
    
    [UMSocialWechatHandler setWXAppId:wechatAPPId appSecret:wechatAPPSecret url:redirectUri];
    [UMSocialQQHandler setQQWithAppId:QQAppId appKey:QQAppKey url:redirectUri];
    [UMSocialSinaHandler openSSOWithRedirectURL:redirectUri];
    
    if([WeiboSDK isWeiboAppInstalled]){
        [WeiboSDK enableDebugMode:YES];
        [WeiboSDK registerApp:sinaAPPKey];
    }
}
-(void)setupBaiduMap
{
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"CjZKaI7hCuBnIPraZHDlfqlM"  generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
}
#pragma mark 检查版本更新
-(void)checkVersion{
//    module= appInfo method=iosVersion
    [[BuaatVolunteerServerSDK sharedInstance]requestVersioniOSWithSuccess:^(NSHTTPURLResponse *response, id responseObject) {
        NSDictionary *responseData=responseObject;
        if([responseObject isKindOfClass:[NSDictionary class]]&&responseData[@"ret"]==nil){
            self.versionInfo=responseData;
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            // app版本
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            
            NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
            
            NSString *appInfo=[NSString stringWithFormat:@"%@.%@",app_Version,app_build];
            [self checkVersionAndUpdate:responseObject[@"regionVersion"] andBankVersion:responseObject[@"bankAddressVersion"]];
//            [self checkVersionAndUpdate:@"1.4" andBankVersion:@"1.4"];
            if(![appInfo isEqualToString:self.versionInfo[@"version"]]){
                UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前App有更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"现在下载", nil];
                [alertView show];
            }
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        
    }];
    
    
    
    /*
    [Utils requestDic:@{@"token":@"sdfsadfsadfasdf",@"module":@"AppInfo",@"method":@"iosVersion",@"requestId":[NSNull new],@"requestParam":@[appInfo]} andRusult:^(id result) {
            
            NSDictionary *responseData =result[@"responseData"];
            self.versionInfo=responseData;
            
            if([responseData isKindOfClass:[NSDictionary class]]){
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                // app版本
                NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
                
                NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
                
                NSString *appInfo=[NSString stringWithFormat:@"%@.%@",app_Version,app_build];
                if(![appInfo isEqualToString:self.versionInfo[@"version"]]){
                    UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前App有更新" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"现在下载", nil];
                    [alertView show];
                }
                
            }
        
    } andError:^(id result) {
        
    }];
     */
}

-(void)checkVersionAndUpdate:(NSString *)cityVersion andBankVersion:(NSString *)bankVersion
{
    [[UserInfoManager sharedManager]refreshUserInfo];
    if (cityVersion!=nil&& [cityVersion isKindOfClass:[NSNull class]]) {
        cityVersion = @"";
    }
    if (bankVersion!=nil&& [bankVersion isKindOfClass:[NSNull class]]) {
        bankVersion = @"";
    }
    
    
    if ([[CityFileManager sharedManager]isNeedToUpdate:cityVersion andType:CityFileType])
    {
        [[CityFileManager sharedManager]getCityFile:^(id result) {
            
        } andDefault:^{
            
        }];
    }
//
//    
//    
    if ([[CityFileManager sharedManager]isNeedToUpdate:bankVersion andType:BankFileType])
    {
        [[CityFileManager sharedManager]getBankFile:^(id result) {
            
        } andDefault:^{
            
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        NSString *urlStr=[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",self.versionInfo[@"packageLocation"]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];

    }else if (buttonIndex==0){
        if(self.versionInfo[@"isForced"]&&[self.versionInfo[@"isForced"] intValue]==1){
            exit(0);
        }
    }
}
- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSLog(@"%@",deviceToken);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.buaa.MemberProject" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MemberProject" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MemberProject.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
